package com.example.mqttclient;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mqttclient.mqtt.MqttService;
import com.example.mqttclient.protocol.AirConditioningMessage;
import com.example.mqttclient.protocol.BoolMessage;
import com.example.mqttclient.protocol.IntLevelMessage;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.google.gson.Gson;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DevicesDemoActivity extends AppCompatActivity implements MqttService.MqttEventCallBack,
        CompoundButton.OnCheckedChangeListener,SeekBar.OnSeekBarChangeListener {

    private TextView connectState, temperatureValue, humidityValue, pm25Value, gasValue, doorStatus;
    private EditText airConditioningValue;
    private MqttService.MqttBinder mqttBinder;
    private String TAG = "MainActivity";
    private Switch parlourLightSwitch, curtain_switch, fan_socket_switch, air_conditioning_switch;
    private Map<String, Integer> subscribeTopics = new HashMap<>();
    private LineChart tempChart, humChart, pm25Chart;
    private List<Entry> tempEntries = new ArrayList<>();
    private List<Entry> humEntries = new ArrayList<>();
    private List<Entry> pm25Entries = new ArrayList<>();

    private TextView lightStatus, fanStatus; // 新增状态显示文本


    private SeekBar lightSeekBar, fanSeekBar;
    private TextView lightLevelText, fanLevelText;
    private int lightLevel = 1;
    private int fanLevel = 2;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mqttBinder = (MqttService.MqttBinder) iBinder;
            mqttBinder.setMqttEventCallBack(DevicesDemoActivity.this);
            if (mqttBinder.isConnected()) {
                connectState.setText("已连接");
                subscribeTopics();
            } else {
                connectState.setText("未连接");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devices_demo);

        // 初始化图表
        tempChart = findViewById(R.id.chart_temperature);
        humChart = findViewById(R.id.chart_humidity);
        pm25Chart = findViewById(R.id.chart_pm25);

        // 初始化数值显示控件
        connectState = findViewById(R.id.dev_connect_state);
        temperatureValue = findViewById(R.id.temperature_value);
        humidityValue = findViewById(R.id.humidity_value);
        pm25Value = findViewById(R.id.pm_value);
        gasValue = findViewById(R.id.gas_value);
        doorStatus = findViewById(R.id.door_status);
        airConditioningValue = findViewById(R.id.air_conditioning_value);

        // 初始化开关控件
        parlourLightSwitch = findViewById(R.id.parlour_light_switch);
        parlourLightSwitch.setOnCheckedChangeListener(this);
        curtain_switch = findViewById(R.id.curtain_switch);
        curtain_switch.setOnCheckedChangeListener(this);
        fan_socket_switch = findViewById(R.id.fan_socket_switch);
        fan_socket_switch.setOnCheckedChangeListener(this);
        air_conditioning_switch = findViewById(R.id.air_conditioning_switch);
        air_conditioning_switch.setOnCheckedChangeListener(this);

        // 初始化档位调节控件
        lightSeekBar = findViewById(R.id.light_seekbar);
        fanSeekBar = findViewById(R.id.fan_seekbar);
        lightLevelText = findViewById(R.id.light_level_text);
        fanLevelText = findViewById(R.id.fan_level_text);

        lightSeekBar.setOnSeekBarChangeListener(this);
        fanSeekBar.setOnSeekBarChangeListener(this);

        // 初始化图表
        initChart(tempChart, "温度（°C）");
        initChart(humChart, "湿度（%）");
        initChart(pm25Chart, "PM2.5（μg/m³）");

        // 绑定MQTT服务
        Intent mqttServiceIntent = new Intent(this, MqttService.class);
        bindService(mqttServiceIntent, connection, Context.BIND_AUTO_CREATE);
    }

    private void initChart(LineChart chart, String description) {
        chart.getDescription().setText(description);
        chart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        chart.getAxisRight().setEnabled(false);
        chart.setTouchEnabled(true);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setPinchZoom(true);
    }

    // SeekBar监听方法
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.light_seekbar:
                lightLevel = progress + 1;
                lightLevelText.setText(lightLevel + "档");
                sendLightState();
                break;
            case R.id.fan_seekbar:
                fanLevel = progress + 1;
                fanLevelText.setText(fanLevel + "档");
                sendFanState();
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {}

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {}



    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.parlour_light_switch:
                try {
                    // 添加状态字段
                    mqttBinder.publishMessage("/test/light1",
                            new Gson().toJson(new BoolMessage(isChecked, isChecked ? "on" : "off")));
                } catch (MqttException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.curtain_switch:
                try {
                    // 添加状态字段
                    mqttBinder.publishMessage("/test/curtain1",
                            new Gson().toJson(new BoolMessage(isChecked, isChecked ? "on" : "off")));
                } catch (MqttException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.fan_socket_switch:
                try {
                    // 添加状态字段
                    mqttBinder.publishMessage("/test/fan1",
                            new Gson().toJson(new BoolMessage(isChecked, isChecked ? "on" : "off")));
                } catch (MqttException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.air_conditioning_switch:
                try {
                    // 添加状态字段
                    String json = new Gson().toJson(new AirConditioningMessage(
                            isChecked,
                            Float.parseFloat(airConditioningValue.getText().toString()),
                            isChecked ? "on" : "off")); // 添加状态
                    mqttBinder.publishMessage("/test/airConditioning", json);
                } catch (MqttException | NumberFormatException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void sendLightState() {
        try {
            boolean isOn = parlourLightSwitch.isChecked();
            // 添加状态字段
            String json = new Gson().toJson(new IntLevelMessage(isOn, lightLevel, isOn ? "on" : "off"));
            mqttBinder.publishMessage("/test/light1", json);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private void sendFanState() {
        try {
            boolean isOn = fan_socket_switch.isChecked();
            // 确保关闭时发送"off"
            String status = isOn ? "on" : "off";
            // 添加状态字段
            String json = new Gson().toJson(new IntLevelMessage(isOn, fanLevel, status));
            mqttBinder.publishMessage("/test/fan1", json);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
    void subscribeTopics() {
        try {
            subscribeTopics.put("/test/temp", 1);
            subscribeTopics.put("/test/hum", 2);
            subscribeTopics.put("/test/pm", 3);
            subscribeTopics.put("/test/gas", 4);
            subscribeTopics.put("/test/door", 5);
            subscribeTopics.put("/test/light1/status", 6);
            subscribeTopics.put("/test/fan1/status", 7);

            for (Map.Entry<String, Integer> entry : subscribeTopics.entrySet()) {
                mqttBinder.subscribe(entry.getKey());
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    void unSubscribeTopics() {
        try {
            for (Map.Entry<String, Integer> entry : subscribeTopics.entrySet()) {
                mqttBinder.unsubscribe(entry.getKey());
            }
            subscribeTopics.clear();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onMqttMessage(String topic, String message) {
        Log.d("MQTT_DEBUG", "Received on topic: " + topic);
        Log.d("MQTT_DEBUG", "Message content: " + message);

        try {
            JSONObject json = new JSONObject(message.trim());
            Integer topicType = subscribeTopics.get(topic);
            if (topicType == null) {
                Log.w("MQTT_DEBUG", "Received unsubscribed topic: " + topic);
                return;
            }

            switch (topicType) {
                case 1: // 温度
                    if (json.has("value")) {
                        float tempValue = (float) json.getDouble("value");
                        temperatureValue.setText(String.format("%.1f", tempValue));
                        tempEntries.add(new Entry(tempEntries.size(), tempValue));
                        updateChart(tempChart, tempEntries);
                    }
                    break;

                case 2: // 湿度
                    if (json.has("value")) {
                        int humValue = json.getInt("value");
                        humidityValue.setText(String.valueOf(humValue));
                        humEntries.add(new Entry(humEntries.size(), humValue));
                        updateChart(humChart, humEntries);
                    }
                    break;

                case 3: // PM2.5
                    if (json.has("value")) {
                        int pmValue = json.getInt("value");
                        pm25Value.setText(String.valueOf(pmValue));
                        pm25Entries.add(new Entry(pm25Entries.size(), pmValue));
                        updateChart(pm25Chart, pm25Entries);
                    }
                    break;

                case 4: // 可燃气体
                    if (json.has("value")) {
                        int gasValue = json.getInt("value");
                        this.gasValue.setText(String.valueOf(gasValue));
                    }
                    break;

                case 5: // 门状态
                    if (json.has("value")) {
                        int doorValue = json.getInt("value");
                        doorStatus.setText(doorValue == 1 ? "开" : "关");
                    }
                    break;

                case 6: // 灯光状态反馈
                    if (json.has("power") && json.has("level")) {
                        boolean power = json.getBoolean("power");
                        int level = json.getInt("level");
                        runOnUiThread(() -> {
                            parlourLightSwitch.setChecked(power);
                            lightSeekBar.setProgress(level - 1);
                            lightLevelText.setText(level + "档");
                        });
                    }
                    break;

                case 7: // 风扇状态反馈
                    if (json.has("power") && json.has("level")) {
                        boolean power = json.getBoolean("power");
                        int level = json.getInt("level");
                        runOnUiThread(() -> {
                            fan_socket_switch.setChecked(power);
                            fanSeekBar.setProgress(level - 1);
                            fanLevelText.setText(level + "档");
                        });
                    }
                    break;
            }
        } catch (Exception e) {
            Log.e("JSON Parse", "Error parsing: " + message, e);
        }
    }


    private void updateChart(LineChart chart, List<Entry> entries) {
        if (entries.isEmpty()) return;

        // 限制数据点数量
        if (entries.size() > 100) {
            entries.remove(0);
            // 更新所有点的X值
            for (int i = 0; i < entries.size(); i++) {
                entries.get(i).setX(i);
            }
        }

        LineDataSet dataSet = new LineDataSet(entries, "");
        dataSet.setColor(getResources().getColor(android.R.color.holo_blue_dark));
        dataSet.setCircleColor(getResources().getColor(android.R.color.holo_red_dark));
        dataSet.setLineWidth(2f);
        dataSet.setCircleRadius(4f);
        dataSet.setDrawValues(false);

        LineData lineData = new LineData(dataSet);
        chart.setData(lineData);
        chart.moveViewToX(entries.size());
        chart.invalidate();
    }

    @Override
    public void onConnectSuccess() {
        connectState.setText("已连接");
        subscribeTopics();
    }

    @Override
    public void onConnectError(String error) {
        Log.d(TAG, "onConnectError: " + error);
        connectState.setText("未连接");
        subscribeTopics.clear();
    }

    @Override
    public void onDeliveryComplete() {
        Log.d(TAG, "publish ok");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mqttBinder.isConnected()) {
            connectState.setText("已连接");
            subscribeTopics();
        } else {
            connectState.setText("未连接");
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unSubscribeTopics();
    }

    @Override
    protected void onDestroy() {
        unbindService(connection);
        super.onDestroy();
    }
}